package com.kukudb.asaproject.controller.api;

import com.kukudb.asaproject.aimodel.chatServer.ChatServerUitl;
import com.kukudb.asaproject.pojo.ResponseMessage;
import com.kukudb.asaproject.pojo.User;
import com.kukudb.asaproject.pojo.UserLicenses;
import com.kukudb.asaproject.pojo.paramsDto.Question;
import com.kukudb.asaproject.serveice.CardKeysImpl;
import com.kukudb.asaproject.serveice.UserLicensesImpl;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController     //接口方法返回对象  转换成json数据
@RequestMapping("/api/server")    // localhost:81/api/user
public class FunctionalApis {
    Logger logger = LoggerFactory.getLogger(FunctionalApis.class);
    @Autowired
    ChatServerUitl chatServerUitl;

    @Autowired
    UserLicensesImpl userLicensesImpl;
    @Autowired
    private CardKeysImpl cardKeysImpl;

    @PostMapping("/ask")
    public ResponseMessage ask(@RequestBody Question question,  HttpSession session) {
        logger.info("question: " + question.toString());
        //查新授权
        User user = (User)session.getAttribute("user");
        UserLicenses userLicenses = new UserLicenses();
        if (!("0".equals(user.getRole()) ||  "1".equals(user.getRole()))) {
            //检查用户额度
             userLicenses = userLicensesImpl.getUserLicenses(user.getUserId());
            if (userLicenses == null) {
                throw new RuntimeException("用户没有授权或者使用记录");
            }
            if (!userLicensesImpl.getPermissions(userLicenses)) {
                throw new RuntimeException("用户额度不足");
            }
            logger.info("userLicenses: " + userLicenses);
        }
        String chatMessage = chatServerUitl.getChatMessage(question.getAnswerText());
        //用户使用成功licenseType
        if ("2".equals(userLicenses.getLicenseType())){
            //增加使用值
            cardKeysImpl.addUsedCont(user.getUserId(), 1);
        }
        return new ResponseMessage(200, "success", chatMessage);

        //返回ResponseMessage对象
    }

    //查询剩余额度
    @GetMapping("/getLicenses")
    public ResponseMessage getLicenses(HttpSession session) {
        User user = (User)session.getAttribute("user");
        UserLicenses userLicenses = new UserLicenses();
        if (!("0".equals(user.getRole()) ||  "1".equals(user.getRole()))) {
            //检查用户额度
            userLicenses = userLicensesImpl.getUserLicenses(user.getUserId());
            if (userLicenses == null) {
                throw new RuntimeException("用户没有授权或者使用记录");
            }
            logger.info("userLicenses: " + userLicenses);
        }
        return new ResponseMessage(200, "success", userLicenses);
    }
}
